package com.example.stargazer.usb_service;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;


public class MainActivity extends ActionBarActivity {

    public static final String TAG = "com.example.stargazer";
    protected final Object threadLock = new Object();//加锁

    byte[] writeBuffer;
    byte[] readBuffer;
    int actualNumBytes;


    public Context global_context;
    public boolean READ_ENABLE_340 = false;
    public String act_string;

    EditText sendEditText;
    TextView receiveText;
    Button sendButton;
    Button openDeviceButton;

    USBDriver usbDriver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        openDeviceButton = (Button)findViewById(R.id.open_device_button);
        sendButton = (Button)findViewById(R.id.button_send);
        receiveText = (TextView)findViewById(R.id.receive_text);

        sendEditText = (EditText)findViewById(R.id.send_editText);

        writeBuffer = new byte[512];
        readBuffer = new byte[512];
        openDeviceButton.setOnClickListener(new OpenDeviceButtonListener());
        sendButton.setOnClickListener(new OnClickSendButtonListener());
        sendButton.setEnabled(false);

        usbDriver = new USBDriver(this, (UsbManager)getSystemService(Context.USB_SERVICE));

        act_string = getIntent().getAction();
        if(act_string.contains("android.intent.action.MAIN")){
            Log.d(TAG, "android.intent.action.MAIN");
        } else if(act_string.contains("android.hardware.usb.action.USB_DEVICE_ATTACHED")){
            Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED");
        }

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        //开启读取线程
        if (!READ_ENABLE_340){
            READ_ENABLE_340 = true;
            ReadThread readThread = new ReadThread(handler_340);
            readThread.start();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class OpenDeviceButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            sendButton.setEnabled(true);
            UsbDevice usbDevice = usbDriver.enumerateDevice();
            if(usbDevice==null){
                Toast.makeText(MainActivity.this, "no device found!",Toast.LENGTH_SHORT).show();
            }
            else{
                usbDriver.openDevice(usbDevice);
            }
            openDeviceButton.setEnabled(false);
        }
    }

    public class OnClickSendButtonListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            int numBytes = 0;
            int mLen = 0;

            if( sendEditText.length() != 0 ){
                numBytes = sendEditText.length();
                for (int count=0; count < numBytes; count++){
                    writeBuffer[count] = (byte)sendEditText.getText().charAt(count);
                }
            }
            try {
                mLen = usbDriver.writeData(writeBuffer, numBytes);
            } catch (IOException e) {
                Toast.makeText(global_context, "WriteData Error", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            if (numBytes != mLen){
                Toast.makeText(global_context, "length error", Toast.LENGTH_SHORT).show();
            }
            Log.d(TAG, "WriteData Length is " + mLen);
        }
    }

    final Handler handler_340 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (actualNumBytes != 0x00 ){
                receiveText.setText(new String(readBuffer, 0, actualNumBytes));
            }
        }
    };

    //显示读取的数据的线程
    private class ReadThread extends Thread{
        Handler handler ;

        ReadThread(Handler handler){
            this.handler = handler;
            this.setPriority(Thread.MIN_PRIORITY);
        }

        @Override
        public void run() {
            while (READ_ENABLE_340){
                Message message = handler.obtainMessage();
                message.what = 0;
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (threadLock){
                    if (usbDriver != null){
                        actualNumBytes = usbDriver.readData(readBuffer, 64);
                    }
                    if (actualNumBytes>0){
                        handler.sendMessage(message);
                        actualNumBytes = 0;
                    }
                }
            }
        }
    }

    @Override
    protected void onStop() {
        if(READ_ENABLE_340) {
            READ_ENABLE_340 = false;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {

        if ( usbDriver != null ){
            if (usbDriver.isConnected()){
                usbDriver.closeDevice();
            }
            usbDriver = null;
        }
        super.onDestroy();
    }
}
